import React, { useEffect, useState } from 'react'
import { Space, Table, Button, Drawer, theme,  Form, Input, Flex, Popconfirm} from 'antd';
import type { TableProps,   } from 'antd';
import { DownOutlined } from '@ant-design/icons'
import { QuestionDataApi, QuestionTypeApi, QuestionSortApi, delQuestionApi, editQuestionApi } from '@/service'
import type { QuestionListItem, QuestionTypeItem, sortItem } from '@/service/type'
import {AdvancedSearchForm} from './components/searchCon'
import style from './Questions.module.scss'
import { useNavigate } from 'react-router-dom';

const Questions = () => {
  // interface QuestionTypeItem {
  //   question: string;
  //   type: string;
  //   classify: string;
  //   time: string;
  //   action: string;
  //   _id: string
  // }
  // interface QuestionType {
  //   name: string;
  //   value: number;
  //   _id: string;
  // }
  // 抽屉
  const [open, setOpen] = useState(false);
  // const token = useTheme();
  const [total, setTotal] = useState(0)
  // const [sortTotal, setSortTotal] = useState(0)
  // 题库数据
  const [questions, setQuestions] = useState<QuestionListItem[]>([])
  // 单选多选分类
  const [questionsSort, setQuestionsSort] = useState<sortItem[]>([])
  const [query, setQuery] = useState({
    page: 1,
    pagesize: 10
   })
   // 题库分类
  const [questionsType, setQuestionsType] = useState<QuestionTypeItem[]>([])
  const typeQuery = {
    ...query,
    question: 123
  }

  
    
  const showDrawer = () => {
    setOpen(true);
  };

  const onClose = () => {
    setOpen(false);
  };
   // 题库数据
  const getQuestionData = async () => {
    try {
      const res = await QuestionDataApi({
        page: query.page,
        pagesize: query.pagesize,
      })
      setQuestions(res.data.data.list)
      console.log(questions)

      setTotal(res.data.data.total)
    } catch (e) {
      console.log(e)
    }
  }
   // 删除数据
   const QuestionsDelData = async (id: string) => {
    try {
      const res = await delQuestionApi(id)
      getQuestionData()
      // setQuestions(res.data.data.list)

    } catch (e) {
      console.log(e)
    }
  }
  // // 编辑数据
  // const QuestionsEditData = async (id: string) => {
  //   try {
  //     const res = await editQuestionApi(id)
  //     getQuestionData()
     
  //   } catch (e) {
  //     console.log(e)
  //   }
  // }

    // 编辑数据
    const QuestionsEditData = async (id: string, values: QuestionListItem) => {
      try {
        const res = await editQuestionApi(id, values);
        getQuestionData();
        setEditingId(undefined);
      } catch (e) {
        console.log(e);
      }
    };
  
  // 物理化学分类
  const QuestionTypeData = async () => {
    try {
      const res = await QuestionTypeApi({
        page: typeQuery.page,
        pagesize: typeQuery.pagesize,
        question: 123
      })
      setQuestionsType(res.data.data.list)
      console.log(res.data.data.list)
    } catch (e) {
      console.log(e)
    }
  }
  // 单选多选分类
  const QuestionSortData = async () => {
    try {
      const res = await QuestionSortApi()
      setQuestionsSort(res.data.data.list)
      console.log(questionsSort)
    } catch (e) {
      console.log(e)
    }
  }
  useEffect(() => {
    getQuestionData()
    QuestionSortData()
    QuestionTypeData()
  }, [])

  useEffect(() => {
    getQuestionData()
  }, [query, ])

  const save = async (id: string) => {
    try {
      //获取到的表单字段值
      const values = await form.validateFields();
      await QuestionsEditData(id, values);
    } catch (error) {
      console.log('Validation failed:', error);
    }
  }
  const cancel = () => {
    setEditingId(undefined);
  }

  const isEditing = (record: QuestionListItem) => record._id === editingId;
  const [form] = Form.useForm()
  const [editingId, setEditingId]= useState<string| number>();
  // 编辑
  const edit = (record: QuestionListItem) => {
    form.setFieldsValue({...record})
    setEditingId(record._id)
  }
  const columns: TableProps<QuestionListItem>['columns'] = [
    {
      key: 'question',
      title: '试题列表',
      dataIndex: 'question',
      align: 'center',
      render: (text, record) => {
        const editable = isEditing(record)
        return editable ? ( 
          <Form.Item 
            name="question" 
            rules={[{ required: true }]} 
          >
            <Input 
              style={{ margin: 0 }} 
              onPressEnter={() => save(record._id)} 
            />
          </Form.Item>
        ) : ( // 如果不是编辑状态
          text 
        );
      }
    },
    { 
      key: 'type',
      title: '分类',
      dataIndex: 'type',
      align: 'center',
      render: (text, record) => {
        const item = questionsSort.find(it => 
          (it.value).toString() === record.type
        )
        const editable = isEditing(record)
        return editable ? ( 
          <Form.Item 
            name="question" 
            rules={[{ required: true }]} 
          >
            <Input 
              style={{ margin: 0 }} 
              onPressEnter={() => save(record._id)} 
            />
          </Form.Item>
        ) : ( // 如果不是编辑状态
          item?.name 
        );
      },
      
    },
    { 
      key: 'classify',
      title: '题型',
      dataIndex: 'classify',
      align: 'center',
      render: (text, record) => {
        const editable = isEditing(record)
        return editable ? ( 
          <Form.Item 
            name="question" 
            rules={[{ required: true }]} 
          >
            <Input 
              style={{ margin: 0 }} 
              onPressEnter={() => save(record._id)} 
            />
          </Form.Item>
        ) : ( // 如果不是编辑状态
          text 
        );
      }
    },
    { 
      key: 'time',
      title: '创建时间',
      dataIndex: 'time',
      align: 'center',
      render: (text, record) => 
        new Date().toLocaleString()
    },
    { 
      key: 'action',
      title: '操作',
      dataIndex: 'action',
      align: 'center',
      render: (text, record) => {
        const editable = isEditing(record)
        return editable? (
          <Flex>
            <Button type='link' onClick={() => save(record._id)}>保存</Button>
            <Popconfirm
              title="确定要取消吗？"
              okText="确定"
              cancelText='取消'
              onConfirm={() => cancel}
            >
            <Button type='link' onClick={() => cancel}>取消</Button>
            </Popconfirm>
          </Flex>
        ) : (
          <Flex>
            <Space>
              <Button
                color='primary'
                variant="solid" 
                onClick={() => edit(record)}
              >编辑</Button>
              <Popconfirm
                title="确定要删除此试卷吗？"
                okText="确定"
                cancelText='取消'
                onConfirm={() => QuestionsDelData(record._id)}
              >
                <Button
                  color='danger'
                  variant="solid"
                  onClick={() => {
                    QuestionsDelData(record._id)
                  }}
                >删除</Button>
              </Popconfirm>
              <Button
                color="cyan"
                variant="outlined"
                onClick={showDrawer}
              >试题详情
              </Button>
              <Drawer
              className={style.drawerBox}
                title="试卷预览"
                
                onClose={onClose}
                open={open}
                width='700'
                // rootStyle={{background: 'rgba(0,0,0,.5)'}}
              
                >
                <Space>
                  <button>导出PDF</button>
                  <button>OK</button>
                </Space>
              </Drawer>
            </Space>
          </Flex>        )
      }
        
    },
  ];
  

  const { token } = theme.useToken();

  const listStyle: React.CSSProperties = {
    lineHeight: '200px',
    textAlign: 'center',
    background: token.colorFillAlter,
    borderRadius: token.borderRadiusLG,
    marginTop: 16,
  };
  const navigate = useNavigate()
  return (
    <div className={style.question}>
      <h1>试题库</h1>
      <Button
      color='primary'
      variant="solid"
      onClick={() => {
        navigate('/question/create-item')
      }}
      >添加试题</Button>
      <AdvancedSearchForm
      questionsType={questionsType}
      questionsSort={questionsSort}/>
      {/* {JSON.stringify(questionsSort)} */}
      <Table<QuestionListItem>
          columns={columns}
          rowKey='question'
          dataSource={questions}
          
          pagination={{
            pageSizeOptions: [5, 10, 15, 20],
            total,
            current: query.page,
            pageSize: query.pagesize,
            onChange: (page, pageSize) => {
              setQuery({
                ...query,
                page,
                pagesize: pageSize
              })
            }
          }}
          
          // bordered
        />
       
    </div>
  )
}

export default Questions